using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;


namespace MyFrame.UI
{

    /// <summary>
    /// 面板基类，提供面板下所有控件
    /// </summary>
    public class BasePanel : MonoBehaviour
    {
        private Dictionary<string, List<UIBehaviour>> controDic = new();

        // Start is called before the first frame update
        void Awake()
        {
            FindChildrenControl<Button>();
            FindChildrenControl<Text>();
            FindChildrenControl<Image>();
            FindChildrenControl<Slider>();
            FindChildrenControl<Toggle>();
            FindChildrenControl<ScrollRect>();
        }

        /// <summary>
        /// 获取控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T GetControl<T>(string name) where T : UIBehaviour
        {
            if (controDic.ContainsKey(name))
            {
                for (int i = 0; i < controDic[name].Count; i++)
                {
                    if (controDic[name][i] is T)
                        return controDic[name][i] as T;
                }
            }

            return null;
        }

        public virtual void ShowMe()
        {
        }

        public virtual void HideMe()
        {
        }

        /// <summary>
        /// 找子对象对应控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        private void FindChildrenControl<T>() where T : UIBehaviour
        {
            T[] controls = GetComponentsInChildren<T>();


            for (int i = 0; i < controls.Length; i++)
            {
                string objName = controls[i].gameObject.name;
                if (!controDic.ContainsKey(objName))
                    controDic.Add(objName, new List<UIBehaviour>());
                else
                    controDic[objName].Add(controls[i]);

                //把button的点击事件也封装了
                if (controls[i] is Button)
                {
                    Button btn = controls[i] as Button;
                    btn.onClick.AddListener(() => { OnClick(objName); });
                }else if( controls[i] is Toggle){
                    Toggle toggle = controls[i] as Toggle;
                    toggle.onValueChanged.AddListener((bool value) => { OnValueChanged(objName, value); });
                }
            }
        }

        protected virtual void OnValueChanged(string toggleName, bool value)
        {
            
        }

        /// <summary>
        /// 直接根据名字switch 执行逻辑，无需手动绑定
        /// </summary>
        /// <param name="objName"></param>
        protected virtual void OnClick(string objName)
        {

        }
    }
}
